/*表单元素-模拟滚动条-固定表格-日期控件*/
(function() {
	var imiScroll = true; //启动模拟滚动条
	//追踪jquery操作dom的行为
	(function() {
		var _attr = $.fn.attr,
			_val = $.fn.val,
			_html = $.fn.html,
			_append = $.fn.append,
			_prepend = $.fn.prepend,
			_replaceWith = $.fn.replaceWith;
		$.fn.extend({
			"attr": function() {
				var _return = _attr.apply(this, arguments);
				window.dateInit(this, arguments);
				return _return;
			},
			"val": function() {
				var _return = _val.apply(this, arguments);
				if(this.is('select') && arguments.length) {
					this.css('display', '').removeAttr('data-wl').next('.select-wl').remove();
					window.fromInit();
				}
				return _return;
			},
			"html": function() {
				var _return = _html.apply(this, arguments);
				if(this.is('select')) {
					this.css('display', '').removeAttr('data-wl').next('.select-wl').remove();
				}
				window.fromInit();
				window.tableInit();
				window.dateInit();
				window.imports();
				return _return;
			},
			"append": function() {
				var _return = _append.apply(this, arguments);
				if(this.is('select')) {
					this.css('display', '').removeAttr('data-wl').next('.select-wl').remove();
				}
				window.fromInit();
				window.tableInit();
				window.dateInit();
				window.imports();
				return _return;
			},
			"prepend": function() {
				var _return = _prepend.apply(this, arguments);
				if(this.is('select')) {
					this.css('display', '').removeAttr('data-wl').next('.select-wl').remove();
				}
				window.fromInit();
				window.tableInit();
				window.dateInit();
				window.imports();
				return _return;
			},
			"replaceWith": function() {
				var _return = _replaceWith.apply(this, arguments);
				if(this.is('select')) {
					this.css('display', '').removeAttr('data-wl').next('.select-wl').remove();
				}
				window.fromInit();
				window.tableInit();
				window.dateInit();
				window.imports();
				return _return;
			}
		});
	})();

	//在点击非select区域时,关闭select的展开
	document.addEventListener('click', function() {
		$('.select-unfold:not([data-unfold])').removeClass('select-unfold');
	});
	//	$(document).on('focus', '.select-input-search', function() {
	//		var $thisPP = $(this.parentNode.parentNode).find('dd').css('display', '');
	//	});
	$(document).on('focus', 'select:disabled + .select-wl .select-input', function() {
		this.blur();
	});
	$(document).on('input', '.select-input-search', function() {
		var thisVal = this.value,
			$thisPP = $(this.parentNode.parentNode),
			noMate = true;
		$thisPP.find('dd').each(function() {
			var itemText = this.innerText;
			if(itemText.indexOf(thisVal) == -1) {
				this.style.display = 'none';
			} else {
				this.style.display = '';
				noMate = false;
			}
		});
		noMate ? $thisPP.addClass('no-mate') : $thisPP.removeClass('no-mate');
	});

	//input搜索
	$(document).on('change', '[data-type="search-ajax"]', function() {
		var thisPre = this.previousElementSibling;
		thisPre.value = this.value;
		$(thisPre).trigger('change');
	});

	//在触发非select的滚动条时,关闭select的展开
	window.addEventListener('scroll', function(event) {
		if((event.target == document) || (event.target.getAttribute('data-select') != "select-dl")) {
			$('.select-unfold').removeClass('select-unfold');
		}
	}, true)
	//form重置时,重置时间控件
	$(document).on('reset', 'form', function() {
		var _this = this;
		setTimeout(function() {
			$(_this).find('[_type="date"]').each(function(i, item) {
				var min = item.getAttribute('min'),
					max = item.getAttribute('max'),
					initMin = item.getAttribute('init-min'),
					initMax = item.getAttribute('init-max');
				(initMin != min) && $(item).attr('min', initMin || '1980-1-1');
				(initMax != max) && $(item).attr('max', initMax || '2050-12-30');
			});
		}, 0)
	});
	//触发开始时间的'改变'事件,改变结束时间限制
	$(document).on('change', '[end]', function() {
		var thisV = this.value;
		var endDom = document.querySelector(this.getAttribute('end'));
		if(endDom) {
			var endV = endDom.value;
			if(endV && (new Date(thisV.replace(/-/g, "\/"))) > (new Date(endV.replace(/-/g, "\/")))) {
				endDom.value = ''
			};
			$(endDom).attr('min', this.value);
		}
	});
	//触发结束时间的'改变'事件,改变开始时间限制
	$(document).on('change', '[start]', function() {
		var thisV = this.value;
		var startDom = document.querySelector(this.getAttribute('start'));
		if(startDom) {
			var startV = startDom.value;
			if(startV && (new Date(thisV.replace(/-/g, "\/"))) < (new Date(startV.replace(/-/g, "\/")))) {
				startDom.value = ''
			};
			$(startDom).attr('max', this.value);
		}
	});

	var queryAll = function(sel) {
		return document.querySelectorAll(sel)
	};

	var after = function(newI, exiI) {
		if(exiI.nextSibling) {
			exiI.parentNode.insertBefore(newI, exiI.nextSibling);
		} else {
			exiI.parentNode.appendChild(newI);
		};
		return exiI;
	};

	window.fromInit = function() {
		var checkAll = queryAll('[type="radio"]:not([data-wl]),[type="checkbox"]:not([data-wl])');
		$.each(checkAll, function(i, item) {

			item.setAttribute('data-wl', '');
			var ins = document.createElement("ins");
			ins.setAttribute('class', item.getAttribute('class') || '');
			after(ins, item);
			if(ins.parentNode.nodeName != 'LABEL') {
				ins.onclick = function() {
					item.click();
				};
			};
			item.style.display = 'none';
		});

		var selectAll = queryAll('select:not([data-wl])');
		var html = document.getElementsByTagName('html')[0];

		$.each(selectAll, function(i, item) {
			var optionAll = item.querySelectorAll('option');
			var inputVal = item.value;
			var optionSelectedI = 0;
			$.each(optionAll, function(i, itemJ) {
				if(itemJ.value == item.value) {
					optionSelectedI = i;
					inputVal = itemJ.innerText || itemJ.text;
					return false;
				}
			});
			if(item.getAttribute('data-type') == 'search') {
				if(optionAll[0].value == inputVal || optionAll[0].innerText == inputVal || optionAll[0].text == inputVal) {
					inputVal = '';
				}
				var selectImi = [
					'<div class="select-title"><input class="select-input select-input-search" type="text" placeholder="' + (optionAll[0].innerText || optionAll[0].text || '直接选择或搜索选择') + '" value="' + inputVal + '"><i class="edge"/></i></div>',
					item.outerHTML.replace(/select/g, "dl").replace(/optgroup/g, "dt").replace(/option/g, "dd")
				].join('');
			} else {
				var selectImi = [
					'<div class="select-title"><input class="select-input" type="text" readonly value="' + inputVal + '"><i class="edge"/></i></div>',
					item.outerHTML.replace(/select/g, "dl").replace(/optgroup/g, "dt").replace(/option/g, "dd")
				].join('');
			};
			var ins = document.createElement("div"),
				$ins = $(ins);
			ins.setAttribute('class', 'select-wl ' + item.getAttribute('class'));
			ins.innerHTML = selectImi;
			var itemOffsetWidth = $(item).outerWidth();
			ins.style.width = itemOffsetWidth + 'px';
			var ins_dl = ins.getElementsByTagName('dl')[0],
				ins_dl_type = ins_dl.getAttribute('data-type'),
				$ins_dl = $(ins_dl);
			ins_dl.getElementsByTagName("dd")[optionSelectedI].setAttribute('selected', '');
			ins_dl.style.width = '';
			ins_dl.style.minWidth = itemOffsetWidth + 'px';
			ins_dl.setAttribute('class', '');
			ins_dl.setAttribute('data-select', 'select-dl');
			item.setAttribute('data-wl', '');
			after(ins, item);
			item.style.display = 'none';

			ins.onclick = function() {
				ins.setAttribute('data-unfold', '');
				setTimeout(function() {
					ins.removeAttribute('data-unfold');
				}, 0)
			};
			var $ins_dl_h = $ins_dl.outerHeight();
			ins.querySelector('.select-title').onclick = function() {
				if($ins.hasClass('select-unfold')) {
					return false;
				};
				var offset = $(this.parentNode).offset();
				$ins.addClass('select-unfold');
				if(offset.top - html.scrollTop + 36 + $ins_dl_h < document.documentElement.clientHeight) {
					$ins_dl.css({
						'top': offset.top - html.scrollTop + 30 + 6,
						'bottom': '',
						'left': offset.left - html.scrollLeft
					})
				} else {
					$ins_dl.css({
						'top': '',
						'bottom': html.clientHeight - (offset.top - html.scrollTop) + 6,
						'left': offset.left - html.scrollLeft
					})
				}

			};
			var optionImiAll = ins.querySelectorAll('dd:not([disabled])');
			$.each(optionImiAll, function(i, itemK) {
				itemK.addEventListener('click', function() {
					$ins.removeClass('select-unfold');
					if(ins_dl_type == 'button-group') {
						return; //如果是下拉按钮组,直接跳出
					};
					$.each(optionImiAll, function(i, itemL) {
						itemL.removeAttribute('selected')
					});
					itemK.setAttribute('selected', '');

					ins.querySelector('.select-input').value = this.innerText;
					var itemV = item.value;
					item.value = (this.getAttribute('value') != null) ? this.getAttribute('value') : this.innerText;
					if(item.value != itemV) {
						$(item).trigger('change');
					}
				})
			});

			//搜索下拉框,只输入没选择的情况
			if($.watchDom && (item.getAttribute('data-type') == 'search')) {
				$ins.find('input').one('focus', function() {
					var $thisPP = $(this.parentNode.parentNode).find('dd').css('display', '');
				});

				var watchSearch = true;
				var searchAuto = (item.getAttribute('data-search') == 'auto');
				$.watchDom(ins, function() {
					if(watchSearch) {
						watchSearch = false;
						var _this = this;
						setTimeout(function() {
							watchSearch = true;
							if(!$ins.hasClass('select-unfold')) {
								var thisVal = ins.querySelector("input").value;
								var searchY = false;

								$.each(optionImiAll, function(i, dd) {
									if(dd.innerText == thisVal) {
										ins.querySelector("input").value = dd.innerText;
										if(dd !== ins.querySelector("dd[selected]")) {
											item.value = (dd.getAttribute('value') != null) ? dd.getAttribute('value') : dd.innerText;
											ins.querySelector("dd[selected]") && ins.querySelector("dd[selected]").removeAttribute('selected');
											dd.setAttribute('selected', '');
											item.querySelector('option[selected]') && item.querySelector('option[selected]').removeAttribute('selected');
											item.querySelectorAll('option:not([disabled])')[i].setAttribute('selected', '');

											$(item).trigger('change');
										}

										searchY = true;
										return false;
									}
								});
								//输入值不匹配,退回为原来的值
								if(!searchY) {
									if(searchAuto) {
										item.querySelector('option[selected]') && item.querySelector('option[selected]').removeAttribute('selected');
										if(item.querySelector(".auto-option")) {
											item.removeChild(item.querySelector(".auto-option"))
										};

										var insInputVal = ins.querySelector("input").value;
										var autoOption = document.createElement("option");
										autoOption.className = "auto-option";
										autoOption.value = insInputVal;
										autoOption.innerText = insInputVal;
										autoOption.text = insInputVal;
										item.appendChild(autoOption);

										autoOption.setAttribute('selected', '');
										$(item).trigger('change');

									} else {
										ins.querySelector("input").value = ins.querySelector("dd[selected]") ? ins.querySelector("dd[selected]").innerText : '';
									}
								};
							};
						}, 60);
					};
				});

			};
		});

		/*var inputListAll = queryAll('[data-list]:not([data-wl])'); $.each(inputListAll, function(i, item) { item.setAttribute('data-wl', '');  var ins = document.createElement("select"); ins.setAttribute('class', 'select-search-ajax'); ins.setAttribute('data-type', 'search-ajax'); ins.style.width = $(item).outerWidth() + 'px'; after(ins, item);  item.addEventListener('click', function() { $(this.nextElementSibling.nextElementSibling.querySelector('.select-title')).trigger('click'); });  var unfold = function() { var dataList = item.getAttribute('data-list').split(','), optionAll = '<option style="display: none;"></option>';  $.each(dataList, function(i, v) { optionAll += '<option value="' + v + '">' + v + '</option>' });  $(ins).html(optionAll);  var ins_ins = ins.nextElementSibling, ins_ins_input = ins_ins.querySelector('.select-title');  ins_ins.style.left = '-' + $(item).outerWidth() + 'px'; ins_ins.style.verticalAlign = 'top'; item.getAttribute('data-list') ? $(ins_ins).removeClass('no-mate') : $(ins_ins).addClass('no-mate'); ins_ins_input.style.display = 'none';  };  unfold(); $.watchDom(item, function() { unfold(); if(document.activeElement == item) { $(item.nextElementSibling.nextElementSibling.querySelector('.select-title')).trigger('click'); } }); });*/

		var numberAll = queryAll('[type="number"]:not([data-wl]),[_type="number"]:not([data-wl])');
		$.each(numberAll, function(i, item) {

			item.setAttribute('data-wl', '');
			var ins = document.createElement("ins"),
				add = document.createElement("ins"),
				minus = document.createElement("ins");
			add.setAttribute('class', 'ins-add');
			minus.setAttribute('class', 'ins-minus');
			ins.appendChild(add);
			ins.appendChild(minus);
			after(ins, item);
			add.onclick = function() {
				var numberVal = parseFloat(item.value) || 0,
					numberStep = parseFloat(item.getAttribute('step')) || 1,
					numberMax = parseFloat(item.getAttribute('max'));
				numberVal = parseInt(numberVal / numberStep) * numberStep;
				if(numberMax != NaN) {
					(numberVal + numberStep <= numberMax) && (item.value = numberVal + numberStep, $(item).trigger('change'));
				} else {
					item.value = numberVal + numberStep, $(item).trigger('change')
				};
			};
			minus.onclick = function() {
				var numberVal = parseFloat(item.value) || 0,
					numberStep = parseFloat(item.getAttribute('step')) || 1,
					numberMin = parseFloat(item.getAttribute('min'));
				numberVal = parseInt(numberVal / numberStep) * numberStep;
				if(numberMin != NaN) {
					(numberVal - numberStep >= numberMin) && (item.value = numberVal - numberStep, $(item).trigger('change'));
				} else {
					item.value = numberVal - numberStep, $(item).trigger('change')
				};
			};
		});

		if(imiScroll && !/WebKit\//.test(navigator.userAgent)) {
			var mscroll = queryAll('.m-scroll:not([data-wl])');
			var mscrollFn = function() {
				$.each(mscroll, function(i, item) {
					item.setAttribute('data-wl', '');
					var $item = $(item);
					$item.slimScroll({
						height: $item.height(),
						allowPageScroll: true,
						disableFadeOut: true,
						railVisible: true,
					});
				});
			};

			if(mscroll.length) {
				if(document.getElementById('slimscroll') && document.getElementById('slimscroll').getAttribute('data-load')) {
					mscrollFn();
				} else {
					var slimscroll = document.createElement("script");
					slimscroll.src = "https://cdn.bootcss.com/jQuery-slimScroll/1.3.8/jquery.slimscroll.min.js";
					slimscroll.id = 'slimscroll';
					document.getElementsByTagName('head')[0].appendChild(slimscroll);
					slimscroll.onload = function() {
						slimscroll.setAttribute('data-load', true);
						mscrollFn()
					}
				}
			}
		}
	};

	window.tableInit = function() {
		var mtable = queryAll('.m-table:not([data-wl])');
		$.each(mtable, function(i, item) {
			var tableKey = 'table-' + parseInt(Math.random() * 1E10);
			item.setAttribute('data-wl', tableKey);
			var styleI = document.createElement("style");
			styleI.id = tableKey;
			document.getElementsByTagName('head')[0].appendChild(styleI);
			var tableFn = function() {
				var leftI = item.scrollLeft,
					topI = item.scrollTop,
					rightI = item.scrollWidth - item.clientWidth - item.scrollLeft,
					bottomI = item.scrollHeight - item.clientHeight - item.scrollTop;
				var styleS = [
					'[data-wl="' + tableKey + '"] .fixed-left{left:' + leftI + 'px;}',
					'[data-wl="' + tableKey + '"] .fixed-top td{top:' + topI + 'px;}',
					'[data-wl="' + tableKey + '"] .fixed-right{right:' + rightI + 'px;}',
					'[data-wl="' + tableKey + '"] .fixed-bottom td{bottom:' + bottomI + 'px;}'
				].join('\n');
				styleI.innerHTML = styleS;
			};
			tableFn();
			item.onscroll = tableFn;
			window.addEventListener('resize', tableFn);
		});
	};
	/*数据表格*/
	window.dataTable = function(arg) {
		return new dTClass(arg);
	};

	var dataCheckedFn = function(config) {
		$(config.elem).find('input.cb-all').change(function() {
			if($(this).prop('checked')) {
				$(config.elem).find('input.cb-item').prop('checked', true);
			} else {
				$(config.elem).find('input.cb-item').prop('checked', false);
			}
		});
		$(config.elem).find('input.cb-item').change(function() {
			if($(config.elem).find('input.cb-item:checked').length == $(config.elem).find('input.cb-item').length) {
				$(config.elem).find('input.cb-all').prop('checked', true);
			} else {
				$(config.elem).find('input.cb-all').prop('checked', false);
			}
		});
		$(config.elem + ' .cb-all').click(function(event) {
			event.stopPropagation();
		});
		$(config.elem + ' .cb-item-disabled').click(function(event) {
			event.stopPropagation();
		});
		$(config.elem + ' .cb-item').click(function(event) {
			event.stopPropagation();
		});
	};

	var dataTableTpl;

	var dTClass = function(config) {
		var _this = this;
		this.config = config || {};
		//dataTableTpl || (dataTableTpl = $.getScript(jsBase + 'data-table.tpl'));
		dataTableTpl || (dataTableTpl = $.ajax({
			type: "get",
			url: jsBase + 'data-table.tpl.js',
			dataType: "script",
			cache: true
		}));

		$.when(layui.use('laytpl'), dataTableTpl).done(function(i, tpls) {
			//_this.config.tpl = tpls[0];
			dataTableTpl = dataTableTplV;
			_this.config.tpl = dataTableTplV;
			layui.laytpl(_this.config.tpl).render(_this.config, function(htmlV) {
				$(_this.config.elem).html(htmlV);
				dataCheckedFn(_this.config);
			})
		});
	};

	dTClass.prototype.update = function(arg) {
		var _this = this;
		arg.data && (_this.config.data = arg.data);
		arg.cols && (_this.config.cols = arg.cols);
		arg.total !== undefined && (_this.config.total = arg.total);
		layui.laytpl(_this.config.tpl).render(_this.config, function(htmlV) {
			document.querySelector("head").removeChild(document.querySelector("#" + document.querySelector(_this.config.elem + ' .m-table').getAttribute('data-wl')));
			$(_this.config.elem).html(htmlV);
			dataCheckedFn(_this.config);
		});
	};

	window.dateInit = function($dom, arg) {
		if($dom && $dom.is('[_type="date"]') && arg.length == 2 && (arg[0] == 'min' || arg[0] == 'max')) {
			if($dom[0].value) {
				if((arg[0] == 'min') && (new Date($dom[0].value.replace(/-/g, "\/")) < new Date(arg[1].replace(/-/g, "\/")))) {
					$dom[0].value = ''
				} else if((arg[0] == 'max') && (new Date($dom[0].value.replace(/-/g, "\/")) > new Date(arg[1].replace(/-/g, "\/")))) {
					$dom[0].value = ''
				}
			};
			var newDate = new Date((arg[1] || (arg[0] == 'min' && '1980-1-1') || (arg[0] == 'max' && '2050-12-30')).replace(/-/g, "\/"));
			var newDateObj = {
				year: newDate.getFullYear(),
				month: newDate.getMonth(),
				date: newDate.getDate(),
				hours: newDate.getHours(),
				minutes: newDate.getMinutes(),
				seconds: newDate.getSeconds()
			};

			var dateKey = $dom[0].getAttribute('data-wl');
			if(arg[0] == 'min') {
				window[dateKey + ''].config.min = newDateObj;
			} else if(arg[0] == 'max') {
				window[dateKey + ''].config.max = newDateObj;
			};
			return;
		}

		var mdate = queryAll('[type="date"]:not([data-wl]),[_type="date"]:not([data-wl])');
		if(mdate.length) {
			layui.use('laydate', function() {
				$.each(mdate, function(i, item) {
					item.setAttribute('type', 'text');
					var dateKey = 'date-' + parseInt(Math.random() * 1E10);
					item.setAttribute('data-wl', dateKey);
					var config = item.getAttribute('config'),
						min = item.getAttribute('min'),
						max = item.getAttribute('max'),
						value = item.value;
					min && !item.getAttribute('init-min') && item.setAttribute('init-min', min);
					max && !item.getAttribute('init-max') && item.setAttribute('init-max', max);
					if(config) {
						eval('config=' + config)
					} else {
						config = {}
					};
					config.elem = item, min && (config.min = min), max && (config.max = max), value && (config.value = value);
					var _done = config.done;
					config.done = function(value, date, endDate) {
						$(this.elem).trigger('change');
						_done && _done(value, date, endDate)
					};
					window[dateKey + ''] = layui.laydate.render(config);
				});
			});
		}
	};
})();

$(function() {
	window.fromInit();
	window.tableInit();
	window.dateInit();
	document.querySelector("html").style.opacity = '';
});